<template>
  <div class="app-container">
    <div class="form-container">
      <el-form status-icon :model="form" :rules="rules" ref="ruleFormRef" label-width="100px">
        <div class="form-title">
          <span class="title-number">1</span>
          <span class="title-text">仓站基本信息</span>
        </div>
        <el-form-item label="仓站名称" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="仓站类型" prop="stationType">
          <el-select @change="getLevelTypeList" v-model="form.stationType" placeholder="请选择仓站类型">
            <el-option v-for="item in siteTypeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="仓站等级" prop="stationLevel">
          <el-select v-model="form.stationLevel" placeholder="请选择仓站等级">
            <el-option v-for="item in siteLevelOptions" :key="item.id" :label="item.levelName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="仓库面积" prop="acreage">
          <el-input v-model="form.acreage"></el-input>
        </el-form-item>
        <el-form-item label="所属地市" prop="city">
          <el-select @change="getCityListDict(true)" v-model="form.city" placeholder="请选择所属地市">
            <el-option v-for="item in cityOptions" :key="item.code" :label="item.name" :value="item.code as string"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属区县" prop="county">
          <el-select v-model="form.county" placeholder="请选择所属区县">
            <el-option v-for="item in countyOptions" :key="item.code" :label="item.name" :value="item.code"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="仓站地址" prop="address">
          <el-input id="address" v-model="form.address" @keydown.enter="searchPlace"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <div class="map-container">
      <div class="mapContainer" id="mapContainer"></div>
    </div>
    <div class="btn-container">
      <!-- 无法判断函数传入值的类型 使用断言的方式 -->
      <el-button type="info" @click="resetForm(ruleFormRef as FormInstance)">重置</el-button>
      <el-button type="primary" v-if="btnFlag" @click="submitAddCompany(ruleFormRef as FormInstance)">保存</el-button>
      <el-button type="primary" v-else @click="submitUpadateCompany(ruleFormRef as FormInstance)">修改</el-button>
    </div>
  </div>
</template>
<script setup lang="tsx" name="addCompany">
import { ref, reactive, onMounted } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { LevelType, Site } from "@/api/interface/province/organizationManage";
import { addSiteAPI, updateSiteAPI, siteDetailAPI, getLevelTypeListAPI } from "@/api/modules/province/organizMangeAPI";
import { useRoute, useRouter } from "vue-router";
import { Dict } from "@/api/interface/dict";
import { getCityListDictAPI } from "@/api/modules/dictAPI";
const route = useRoute();
// addFormType 已经在proOrganization.d.ts中通过declare定义过全局变量不用去单独引入
let form = ref<Site.SiteAddParams>({
  province: JSON.parse(localStorage.getItem("userInfo") as string).province,
  city: "",
  cityName: "",
  county: "",
  countyName: "",
  name: "",
  stationType: "",
  stationLevel: "",
  address: "",
  longitude: "9",
  latitude: "10",
  remark: ""
});
const rules = reactive<FormRules<typeof rules>>({
  name: [
    { required: true, message: "请输入仓站名称", trigger: "blur" },
    { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" }
  ],
  stationType: [{ required: true, message: "请选择仓站类型", trigger: "blur" }],
  city: [{ required: true, message: "请选择所属地市", trigger: "blur" }],
  county: [{ required: true, message: "请选择所属区县", trigger: "blur" }]
});
const ruleFormRef = ref<FormInstance>();
let btnFlag = ref<boolean>(true);

let map = ref<any>();
let placeSearch = ref<any>();
let districtSearch = ref<any>();
let polygons = ref<any>();
let auto = ref<any>();
let cityName = ref<string>("吴忠");
onMounted(() => {
  initMap();
  // if(route.query.id) companyDetail(route.query.id as number);
  console.log("路由信息", route.query);
  btnFlag.value = true;
  getCityListDict(false);
  if (route.query.id != undefined) {
    siteDetail(route.query.id as string);
    btnFlag.value = false;
  }
});
const initMap = (): void => {
  //@decription: 初始化地图
  // 需要再次声明全局变量，否则会报错
  window._AMapSecurityConfig = {
    securityJsCode: "e741cd4020ecd80db4d0823c5a7add61"
  };
  AMapLoader.load({
    key: "6e7f26ec5e8f0af59f064c53e5fe2654", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ["AMap.PlaceSearch", "AMap.AutoComplete", "AMap.Scale", "AMap.DistrictSearch"] //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
  })
    .then(AMap => {
      map.value = new AMap.Map("mapContainer", {
        // 设置地图容器id
        viewMode: "3D", // 是否为3D地图模式
        zoom: 15, // 初始化地图级别
        center: [106.253336, 38.446641], // 初始化地图中心点位置
        resizeEnable: true //是否监控地图容器尺寸变化
      });
      AMap.plugin(["AMap.PlaceSearch", "AMap.AutoComplete"], function () {
        let autoOptions = reactive<any>({
          input: "address",
          city: "银川" //城市
        });
        auto.value = new AMap.AutoComplete(autoOptions);
        placeSearch.value = new AMap.PlaceSearch({
          map: map.value,
          pageSize: 10, // 单页显示结果条数
          pageIndex: 1, // 初始页码
          city: "银川", //城市
          panel: "panel", // 结果列表容器
          autoFitView: true //是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        }); //构造地点查询类
        placeSearch.value.on("markerClick", function (e) {
          console.log("点击的信息", e);
          form.value.longitude = e.data.location.lng;
          form.value.latitude = e.data.location.lat;
          form.value.address = e.data.name;
          // console.log("表单信息", form);
        }); //设置城市
        // placeSearch.search(_this.form.address)
        auto.value.on("select", function (e) {
          // console.log("执行函数", e);
          placeSearch.value.setCity(e.poi.adcode);
          placeSearch.value.search(e.poi.name); //关键字查询查询
          form.value.address = e.poi.name;
          console.log("表单信息", form);
          // placeSearch.
          // marker.setPosition(e.poi.location); //设置点标记位置
        }); //注册监听，当选中某条记录时会触发
      });
      let opts = ref<{
        subdistrict: number;
        extensions: string;
        level: string;
      }>({
        subdistrict: 0, //获取边界不需要返回下级行政区
        extensions: "all", //返回行政区边界坐标组等具体信息
        level: "city" //查询行政级别为 市
      });
      districtSearch.value = new AMap.DistrictSearch(opts);
      districtSearch.value.search(cityName.value, function (status, result) {
        console.log(status, result);
        if (polygons.value) {
          map.value.remove(polygons.value); //清除上次结果
          polygons.value = null;
        }
        if (!result || !result.districtList || !result.districtList[0]) {
          // log.warn("请正确填写名称或更新其他名称");
          return;
        }
        let bounds = ref<any>(result.districtList[0].boundaries);
        if (bounds.value) {
          //生成行政区划polygon
          for (let i = 0; i < bounds.value.length; i += 1) {
            //构造MultiPolygon的path
            bounds[i] = [bounds[i]];
          }
          polygons.value = new AMap.Polygon({
            strokeWeight: 1,
            path: bounds,
            fillOpacity: 0.4,
            fillColor: "#80d8ff",
            strokeColor: "#0091ea"
          });
          map.value.add(polygons.value);
          map.value.setFitView(polygons.value); //视口自适应
        }
      });
    })
    .catch(e => {
      console.log(e);
    });
};
const searchPlace = (): void => {
  placeSearch.value.search(form.value.address, (status, result): void => {
    console.log(status);
    console.log(result);
    // console.log("表单信息", form);
  });
};
//表单的校验不要按照element-plus的规则来，自己定义规则，否则校验会一直通过
const submitAddCompany = (formEl: FormInstance) => {
  console.log("执行函数", formEl);
  // if (!formEl) return;
  formEl.validate(valid => {
    console.log("验证结果", valid);
    if (valid) {
      addSite();
    } else {
      ElMessage.error("请检查输入项");
    }
  });
};
const submitUpadateCompany = (formEl: FormInstance) => {
  console.log("执行函数", formEl);
  // if (!formEl) return;
  formEl.validate(valid => {
    console.log("验证结果", valid);
    if (valid) {
      upadateSite();
    } else {
      ElMessage.error("请检查输入项");
    }
  });
};

const resetForm = (formEl: FormInstance) => {
  // if (!formEl) return;
  formEl.resetFields();
};

const siteTypeOptions = ref<
  {
    label: string;
    value: string;
  }[]
>([
  { label: "驿站", value: "1" },
  { label: "中转仓", value: "2" },
  { label: "中心仓", value: "3" }
]);
const siteLevelOptions = ref<any>([]);
const siteDetail = async (id: string) => {
  const { code, data } = await siteDetailAPI(id);
  console.log("详情信息", data);
  if (code == "200" && data) {
    form.value = data.detail;
    getCityListDict(true);
  }
  // if (data) return (form.value = data.detail);
};
const router = useRouter();
const addSite = async () => {
  form.value.cityName = cityOptions.value.find(item => String(item.code) == String(form.value.city))?.name as string;
  form.value.countyName = countyOptions.value.find(item => String(item.code) == String(form.value.county))?.name as string;
  const { code, msg } = await addSiteAPI(form.value);
  if (code == "200") {
    ElMessage.success("保存成功");
    router.push({ path: "/provinceLevel/proOrganization/proSite/proSiteManage" });
  } else {
    ElMessage.error("保存失败" + msg);
  }
};
const upadateSite = async () => {
  form.value.cityName = cityOptions.value.find(item => String(item.code) == String(form.value.city))?.name as string;
  form.value.countyName = countyOptions.value.find(item => String(item.code) == String(form.value.county))?.name as string;
  const { code, msg } = await updateSiteAPI(form.value);
  if (code == "200") {
    ElMessage.success("修改成功");
    router.push({ path: "/provinceLevel/proOrganization/proSite/proSiteManage" });
  } else {
    ElMessage.error("修改失败," + msg);
  }
};
// const levelTypeList = ref<LevelType.Data>({
//   post: [],
//   transferWarehouse: [],
//   centralWarehouse: []
// });
const getLevelTypeList = async () => {
  const levelform = ref<LevelType.AddLevelType>({
    province: JSON.parse(localStorage.getItem("userInfo") as string).province,
    stationType: form.value.stationType,
    levelName: ""
  });
  const { code, data } = await getLevelTypeListAPI(levelform.value);
  if (code == "200" && data) {
    if (form.value.stationType == "1") {
      siteLevelOptions.value = data.post;
    } else if (form.value.stationType == "2") {
      siteLevelOptions.value = data.transferWarehouse;
    } else {
      siteLevelOptions.value = data.centralWarehouse;
    }
  }
};
const cityOptions = ref<Dict.CityListData[]>([]);
const countyOptions = ref<Dict.CityListData[]>([]);
const getCityListDict = async (val: boolean) => {
  const parentCode = ref<string>("");
  if (val) {
    parentCode.value = form.value.city as string;
    cityName.value = cityOptions.value.find(item => String(item.code) == String(form.value.city))?.name as string;
    initMap();
  } else {
    parentCode.value = JSON.parse(localStorage.getItem("userInfo") as string).province;
  }
  const { data, code } = await getCityListDictAPI({
    parentCode: parentCode.value
  });
  if (code == "200" && data) {
    if (val) {
      countyOptions.value = data;
    } else {
      cityOptions.value = data;
    }
    // initMap();
  } else {
    ElMessage.error("获取城市列表失败");
  }
};
</script>
<style lang="scss" scoped>
.app-container {
  padding: 10px;
  background-color: white;
  .form-container {
    box-sizing: border-box;
    display: inline-block;
    width: 50%;
    padding: 10px;
    .form-title {
      margin-bottom: 15px;
      margin-left: 25px;
      .title-number {
        display: inline-block;
        width: 25px;
        height: 25px;
        font-size: 13px;
        line-height: 25px;
        color: white;
        text-align: center;
        vertical-align: middle;
        background-color: #009688;
        border-radius: 50%;
      }
      .title-text {
        display: inline-block;
        margin-left: 10px;
        font-size: 13px;
        vertical-align: middle;

        // font-weight: bold;
      }
    }
  }
  .map-container {
    box-sizing: border-box;
    display: inline-block;
    width: 50%;
    padding: 10px;
    vertical-align: top;
    .mapContainer {
      height: 450px;
    }
  }
  .btn-container {
    margin-top: 20px;
    text-align: center;
  }
}
::v-deep .el-form-item__label {
  font-size: 13px;
}
</style>
